package com.asktgapp.user.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.JGColor;
import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiConfig;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.dialog.ChoosePayWayFragment;
import com.asktgapp.dialog.ChooseTypeFragment;
import com.asktgapp.model.DeviceTypeVO;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.ChooseBrandActivity;
import com.asktgapp.user.activity.ChooseCityActivity;
import com.asktgapp.user.activity.SubIDCardActivity;
import com.asktgapp.user.activity.WebViewActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.utils.SelectPhotoDialogFragment;
import com.bigkoo.pickerview.TimePickerView;
import com.jph.takephoto.model.TImage;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * time:2018/1/10
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class AuthenticateFragment extends BaseFragment {
    //姓名
    @InjectView(R.id.et_auth_name)
    EditText mNameEt;
    //性别
    @InjectView(R.id.tv_auth_sex)
    TextView mSexTv;
    //身份证
    @InjectView(R.id.et_auth_ID_card)
    EditText mIDCardEt;
    //所在公司
    @InjectView(R.id.et_auth_company)
    EditText mCompanyEt;
    //公司职位
    @InjectView(R.id.et_auth_job)
    EditText mJobEt;
    //擅长领域
    @InjectView(R.id.et_auth_strong_point)
    TextView mStrongPoint;
    //自我介绍
    @InjectView(R.id.et_auth_introduction)
    EditText mSelfIntroduciton;
    //下一步
    @InjectView(R.id.tv_auth_next)
    TextView mNextStep;
    //法律协议
    @InjectView(R.id.tv_law_fb)
    TextView mLawText;
    //勾选
    @InjectView(R.id.cb_law)
    CheckBox mCb;


    //咨询价格
    @InjectView(R.id.etPrice)
    EditText etPrice;
    //所在地址
    @InjectView(R.id.tvAddress)
    TextView tvAddress;
    @InjectView(R.id.startTime)
    TextView startTime;
    @InjectView(R.id.endTime)
    TextView endTime;
    @InjectView(R.id.tvGoodAtBrand)
    TextView tvGoodAtBrand;
    @InjectView(R.id.etPhone)
    EditText etPhone;
    @InjectView(R.id.etRecommend)
    EditText etRecommend; //推荐理由

    @InjectView(R.id.et_auth_introduction1)
    EditText et_auth_introduction1;//推荐理由1
    @InjectView(R.id.et_auth_introduction2)
    EditText et_auth_introduction2;//推荐理由2
    @InjectView(R.id.et_auth_introduction3)
    EditText et_auth_introduction3;//推荐理由3
    @InjectView(R.id.etTraining)
    EditText etTraining; //培训经历
    private List<String> uri;
    @InjectView(R.id.rl_head)
    RelativeLayout mHeadRl;
    @InjectView(R.id.iv_head)
    ImageView mHead;
    private String path;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_authenticate, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        uri = new ArrayList<>();
        mNextStep.setOnClickListener(this);
        startTime.setOnClickListener(this);
        endTime.setOnClickListener(this);
        tvAddress.setOnClickListener(this);
        mStrongPoint.setOnClickListener(this);
        tvGoodAtBrand.setOnClickListener(this);
        mHeadRl.setOnClickListener(this);
        mSexTv.setOnClickListener(this);
        mLawText.setOnClickListener(this);
    }

    private void doNext() {
        String name = mNameEt.getText().toString().trim();
        String sex = mSexTv.getText().toString().trim();
        String IDCard = mIDCardEt.getText().toString().trim();
        String company = mCompanyEt.getText().toString().trim();
        String strongPoint = mStrongPoint.getText().toString().trim();
        String introduction = mSelfIntroduciton.getText().toString().trim();
        String position = mJobEt.getText().toString().trim();
        String price = etPrice.getText().toString().trim();
        String address = tvAddress.getText().toString().trim();
        String goodAtBrand = tvGoodAtBrand.getText().toString().trim();
        String training = etTraining.getText().toString();
        String onlineTime = startTime.getText().toString() + "-" + endTime.getText().toString();
        String recommendT = et_auth_introduction1.getText().toString();

//        String etPhone =
        if (Util.isEmpty(name) || Util.isEmpty(IDCard) || Util.isEmpty(strongPoint) || Util.isEmpty(introduction)
                || Util.isEmpty(price) || Util.isEmpty(address) || Util.isEmpty(goodAtBrand) || Util.isEmpty(onlineTime) || Util.isEmpty(recommendT)) {
            showTost("请完善信息！", 1);
        } else {
            String recommend = "";

            if (!TextUtils.isEmpty(et_auth_introduction1.getText().toString()))
                recommend += et_auth_introduction1.getText().toString() ;

            if (!TextUtils.isEmpty(et_auth_introduction2.getText().toString()))
                recommend += "##" + et_auth_introduction2.getText().toString();
            if (!TextUtils.isEmpty(et_auth_introduction3.getText().toString()))
                recommend += "##" + et_auth_introduction3.getText().toString();



            if (!Util.doAuthentication(IDCard)) {
                showTost("请输入合法格式的身份证号码", 0);
                return;
            }

            if (!mCb.isChecked()) {
                showTost("请先阅读并勾选《工程师认证协议》", 0);
                return;
            }
            if (TextUtils.isEmpty(path)) {
                showTost("请上传头像", 0);
                return;
            }
            // TODO: 2018/1/10 传递参数操作
            Intent intent = new Intent(getActivity(), SubIDCardActivity.class);
            Bundle bundle = new Bundle();
            if (!Utils.noContainsEmoji(name, company, IDCard, strongPoint, introduction, position)) {
                showTost("不支持输入enmoji表情", 1);
                return;
            }

            bundle.putString("realname", name);
            if (sex.equals("男")) {
                bundle.putInt("gender", 0);
            } else {
                bundle.putInt("gender", 1);
            }
            bundle.putString("company", company);
            bundle.putString("cardNo", IDCard);
            bundle.putString("goodFeild", strongPoint);
            bundle.putString("description", introduction);
            bundle.putString("position", position);
            bundle.putString("headImg", path);
            Log.e("headImg", path);
            bundle.putString("price", price);
            bundle.putString("province", mAreaId);
            bundle.putString("city", mCityId);
            bundle.putString("brand", mSelectedBrandId);
            bundle.putString("onlineTime", onlineTime);
            bundle.putString("recommendReason", recommend);
            bundle.putString("trainExperience", training);

            intent.putExtra("info", bundle);
            startActivity(intent);
            getActivity().finish();
        }

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_law_fb:
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("url", ApiConfig.LAW_URL);
                intent.putExtra("type", 1);
                getActivity().startActivity(intent);
                break;
            case R.id.tv_auth_sex:
                final List<String> list = new ArrayList<>();
                list.add("男");
                list.add("女");
                ChoosePayWayFragment choosePayWayFragment = new ChoosePayWayFragment(new ChoosePayWayFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mSexTv.setText(s[0]);
                    }
                }, list, "请选择性别");
                choosePayWayFragment.show(getFragmentManager(), "choosePayWayFragment");
                break;
            case R.id.endTime:
                getBaseActivity().hideSoftKeybord();
                showTimeS(false);
                break;
            case R.id.startTime:
                getBaseActivity().hideSoftKeybord();
                showTimeS(true);
                break;
            case R.id.tv_auth_next:
                doNext();
                break;
            case R.id.tvAddress:
                Intent address = new Intent(getActivity(), ChooseCityActivity.class);
                startActivityForResult(address, 300);
                break;
            case R.id.et_auth_strong_point:
                ChooseTypeFragment chooseTypeFragment = new ChooseTypeFragment(new ChooseTypeFragment.Callback() {
                    @Override
                    public void onSelect(String... s) {
                        mStrongPoint.setText(s[1]);
                        mSelectedTypeId = s[0];
                    }
                }, mTypeList, "请选择擅长的设备类型");
                chooseTypeFragment.show(getFragmentManager(), "ChooseTypeFragment");

                break;
            case R.id.tvGoodAtBrand:
                if (Util.isEmpty(mStrongPoint.getText().toString().trim())) {
                    showTost("请先选择设备擅长的类型", 1);
                    return;
                }
                Intent intent1 = new Intent(getActivity(), ChooseBrandActivity.class);
                intent1.putExtra("typeId", mSelectedTypeId);
                startActivityForResult(intent1, 200);
                break;
            case R.id.rl_head:
                SelectPhotoDialogFragment selectPhotoDialogFragment = new SelectPhotoDialogFragment(new SelectPhotoDialogFragment.setResult() {
                    @Override
                    public void setResult(ArrayList<TImage> mImages) {
                        uri.clear();
                        path = mImages.get(0).getPath();
                        uri.add(path);
                        ImageDisplayUtil.loadCircleHeadImage(getActivity(), mHead, path);
//                        UpdateHeadImg();

                    }
                }, 1);
                selectPhotoDialogFragment.show(getFragmentManager(), "selectPhotoDialogFragment");


                break;
        }

    }

    private void showTimeS(final boolean isStart) {
        TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date2, View v) {//选中事件回调
                if (isStart) {
                    Log.e("time", date2.toString());
                    startTime.setText(Util.getShorDateH(date2));
                } else {
                    endTime.setText(Util.getShorDateH(date2));
                }
//                if (!Utils.isGoneDate(Util.DateToStr(date2, "yyyy-MM-dd"))) {
//                    showTost("不能选择将来的时间！", 1);
//                }
//                else
//                    mMadeDate.setText(Util.DateToStr(date2, "yyyy-MM-dd"));

            }
        })
                .setType(TimePickerView.Type.HOURS_MINS)//默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentSize(20)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
//                        .setTitleText("请选择时间")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTextColorCenter(Color.BLACK)//设置选中项的颜色
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(JGColor.APP_BASIC_BLUE)//确定按钮文字颜色
                .setCancelColor(JGColor.APP_BASIC_BLUE)//取消按钮文字颜色
//                        .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                        .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                        .setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//默认是1900-2100年
//                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                        .setRangDate(startDate,endDate)//起始终止年月日设定
//                        .setLabel("年","月","日","时","分","秒")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                        .isDialog(true)//是否显示为对话框样式
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show();
    }


    private String mSelectedBrandId, mSelectedTypeId;
    private String mAreaId, mCityId;
    private List<DeviceTypeVO> mTypeList = new ArrayList<>();

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 200) {
                tvGoodAtBrand.setText(data.getStringExtra("brand"));
                mSelectedBrandId = data.getStringExtra("brandId");
            }
            if (requestCode == 300) {
                mAreaId = data.getStringExtra("areaId");
                mCityId = data.getStringExtra("cityId");
                tvAddress.setText(data.getStringExtra("area") + "  " + data.getStringExtra("city"));
            }
        }
    }

    @Override
    public void loadData() {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        Call<ApiResponseBody<List<DeviceTypeVO>>> call = apiservice.getTypeList(params);
        call.enqueue(new Callback<ApiResponseBody<List<DeviceTypeVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Response<ApiResponseBody<List<DeviceTypeVO>>> response) {
                if (response.isSuccessful()) {
                    mTypeList = response.body().getResult();
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<DeviceTypeVO>>> call, Throwable t) {
                ApiException apiException = ExceptionHandle.handleException(t);
                showTost(apiException.getMessage(), 1);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }
}
